<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .advert_wrapper {
            width: 300px;
            /* height: 400px; */
            background-color: #f6f6f6;
            position: fixed;
            right: 5px;
            bottom: 5px;
            display: none;
        }

        .advert_wrapper .advert_header {
            display: flex;
            line-height: 30px;
            font-size: 14px;
            position: relative;
        }

        .advert_wrapper .advert_header .advert_close {
            position: absolute;
            right: 0;
            top: 0;
            background-color: red;
            width: 30px;
            height: 30px;
            text-align: center;
            line-height: 30px;
        }

        .advert_main {
            width: 100%;
        }

        .advert_main video {
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="advert_wrapper">
        <div class="advert_header">
            <div class="advert_title">距离广告关闭还有10秒</div>
            <div class="advert_close">x</div>
        </div>
        <div class="advert_main">
            <a href="https://www.baidu.com">
                <video src="../video/ad.mp4" autoplay muted loop> </video>
            </a>
        </div>
    </div>
</body>

<script>
    var advertWrapper = document.getElementsByClassName("advert_wrapper")[0];
    var advertTitle = document.getElementsByClassName("advert_title")[0];
    var advertClose = document.getElementsByClassName("advert_close")[0];

    var timeoutTimer = null; // 全局 记录延时器的编号
    var intervalTimer = null;  // 全局 记录计时器的编号

    advertLoop();


    // 问题:
    // 点击close按钮 -> 延时器清除 -> 但是此时计时器已经启动 -> 倒计时完毕再次调用advertLoop()  -> 变相来说清除了,但是并没有完全清除
    // 有良心的广告商: 延时器清除,再清除计时器 => 两个都不跑 
    // 黑心的广告商:   延时器清除,再清除计时器 => 两个都不跑  => 在调用 advertLoop();
    advertClose.onclick = function () {
        advertWrapper.style.display = "none";
        clearTimeout(timeoutTimer);
        clearInterval(intervalTimer);
        advertLoop(5000);
    }

    function advertLoop(delay) {
        delay = delay == undefined ? 5000 : delay;

        clearTimeout(timeoutTimer);
        timeoutTimer = setTimeout(function () {
            advertWrapper.style.display = "block";

            var num = 10;
            advertTitle.innerText = `距离广告关闭还有${num}秒`;
            intervalTimer = setInterval(function () {
                num--;
                advertTitle.innerText = `距离广告关闭还有${num}秒`;
                if (num <= 0) {
                    clearInterval(intervalTimer);
                    advertWrapper.style.display = "none";

                    advertLoop();
                }
            }, 1000)
        }, delay);
    }


</script>

</html>